'use client'; // 声明这是一个客户端组件，因为我们需要使用 state 和 effects

import { useState, FormEvent } from 'react';
import Link from 'next/link';
import { useNotes, useCreateNote, useDeleteNote } from '@/shared/api/notes';
import { useWeather } from '@/shared/api/weather';

// 定义错误类型
interface ErrorWithMessage {
  message: string;
}

export default function HomePageClient() {
  const [newNote, setNewNote] = useState('');
  const [deletingNoteId, setDeletingNoteId] = useState<number | null>(null); // 跟踪正在删除的笔记 ID

  // 使用新的 hooks
  const { data: notes = [], isLoading, error } = useNotes();
  const { mutate: createNote, isPending: isCreatingNote } = useCreateNote();
  const { mutate: deleteNote } = useDeleteNote(); // 移除了未使用的 isDeletingNote

  // 使用 useWeather hook 获取天气数据
  const { data: weather, isLoading: weatherLoading, error: weatherError, isFetching: weatherFetching } = useWeather({ city: '河南漯河' });

  // 处理添加新便利贴
  const handleAddNote = async (e: FormEvent) => {
    e.preventDefault();
    if (!newNote.trim()) return;

    createNote({ content: newNote }, {
      onSuccess: () => {
        setNewNote(''); // 清空输入框
      },
      onError: (err: ErrorWithMessage) => {
        console.error('创建笔记失败:', err.message);
      }
    });
  };

  // 处理删除便利贴
  const handleDeleteNote = (id: number) => {
    setDeletingNoteId(id); // 设置正在删除的笔记 ID
    deleteNote(id, {
      onSuccess: () => {
        setDeletingNoteId(null); // 删除成功后清除 ID
      },
      onError: (err: ErrorWithMessage) => {
        console.error('删除笔记失败:', err.message);
        setDeletingNoteId(null); // 删除失败后清除 ID
      }
    });
  };

  return (
    <div className="flex flex-col items-center min-h-screen bg-gray-900 text-white p-8">
      <h1 className="text-5xl font-bold mb-8">我的便利贴</h1>

      {/* 导航链接到学习页面 */}
      <div className="mb-6 flex flex-wrap gap-4 justify-center">
        <Link href="/tailwind-learn" className="px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg transition-colors">
          学习 Tailwind CSS
        </Link>
        <Link href="/shared-layout/page-one" className="px-4 py-2 bg-purple-600 hover:bg-purple-700 rounded-lg transition-colors">
          共享布局示例
        </Link>
        <Link href="/shadcn-learn" className="px-4 py-2 bg-green-600 hover:bg-green-700 rounded-lg transition-colors">
          学习 shadcn/ui
        </Link>
        <Link href="/tanstack-learn" className="px-4 py-2 bg-yellow-600 hover:bg-yellow-700 rounded-lg transition-colors">
          学习 TanStack Query
        </Link>
        <Link href="/cms-learn" className="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 rounded-lg transition-colors">
          学习 CMS Service
        </Link>
        <Link href="/semantic-html-learn" className="px-4 py-2 bg-teal-600 hover:bg-teal-700 rounded-lg transition-colors">
          学习 Semantic HTML
        </Link>
        <Link href="/shared-data-demo" className="px-4 py-2 bg-orange-600 hover:bg-orange-700 rounded-lg transition-colors">
          共享数据示例
        </Link>
        <Link href="/eventbus-demo" className="px-4 py-2 bg-red-600 hover:bg-red-700 rounded-lg transition-colors">
          事件总线示例
        </Link>
      </div>

      {/* 天气信息展示 */}
      <div className="w-full max-w-md mb-8 p-4 bg-gray-800 rounded-lg">
        {/* 更新标题以反映新城市 */}
        <h2 className="text-2xl font-bold mb-4">河南漯河天气</h2>
        {weatherLoading ? (
          <p>天气数据加载中...</p>
        ) : weatherError ? (
          <div>
            <p className="text-red-500">获取天气数据失败: {weatherError.message}</p>
            {weatherFetching && <p className="text-yellow-500">正在重试...</p>}
          </div>
        ) : weather ? (
          <div>
            <p>城市: {weather.location}</p>
            <p>温度: {weather.temp_c}°C</p>
            <p>天气: {weather.condition}</p>
            {weather.location.includes('模拟数据') && (
              <p className="text-yellow-500 text-sm mt-2">注意: 正在使用模拟数据，因为天气服务暂时不可用</p>
            )}
          </div>
        ) : (
          <p>无法获取天气数据</p>
        )}
      </div>

      {/* 添加便利贴的表单 */}
      <form onSubmit={handleAddNote} className="w-full max-w-md mb-8">
        <div className="flex gap-2">
          <input
            type="text"
            value={newNote}
            onChange={(e) => setNewNote(e.target.value)}
            placeholder="写下新的想法..."
            className="flex-grow p-3 bg-gray-800 border border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            disabled={isCreatingNote}
          />
          <button
            type="submit"
            className="bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-6 rounded-lg transition-colors disabled:opacity-50"
            disabled={isCreatingNote}
          >
            {isCreatingNote ? '添加中...' : '添加'}
          </button>
        </div>
      </form>

      {/* 显示加载、错误或便利贴列表 */}
      <div className="w-full max-w-md">
        {isLoading && <p>加载中...</p>}
        {error && <p className="text-red-500">{error.message}</p>}
        {!isLoading && !error && (
          <ul className="space-y-4">
            {notes.map((note) => (
              <li
                key={note.id}
                className="flex items-center justify-between bg-gray-800 p-4 rounded-lg shadow-md"
              >
                <span className="text-lg">{note.content}</span>
                <button
                  onClick={() => handleDeleteNote(note.id)}
                  className="text-gray-400 hover:text-red-500 transition-colors disabled:opacity-50"
                  disabled={deletingNoteId === note.id} // 只禁用正在删除的笔记按钮
                >
                  {deletingNoteId === note.id ? '删除中...' : '×'} {/* 只对正在删除的笔记显示删除中... */}
                </button>
              </li>
            ))}
          </ul>
        )}
      </div>
    </div>
  );
}
